package com.xingfei.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * AOP处理请求（统一处理日志）
 * @author: chenxingfei
 * @time: 2017/3/17  17:13
 * To change this template use File | Settings | File Templates.
 */
@Aspect
@Component
public class HttpAspect {
    // 日志
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
    /**
     * 抽取日志处理切面表达式
     */
    @Pointcut("execution(public * com.xingfei.blog.controller.*.*(..))")
    public void log(){}

    /**
     * 处理进入控制器之前http请求
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes  requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            if(request != null){
                //访问路径
                logger.info(">>>AOP拦截之RUL={}",request.getRequestURL());
                //方法
                logger.info(">>>AOP拦截之method={}",request.getMethod());
                //ip
                logger.info(">>>AOP拦截之IP={}",request.getRemoteAddr());
                //类方法
                logger.info(">>>AOP拦截之class_method={}",joinPoint.getSignature().getDeclaringType()+"_"+joinPoint.getSignature().getName());
                //参数
                logger.info(">>>AOP拦截之参数={}",joinPoint.getArgs());
            }
        }
    }

    /**
     * 处理控制器返回响应请求
     */
    @After("log()")
    public void doAfter(){

    }

    /**
     * 处理控制器返回响应请求
     */
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        if(object!=null){
            logger.info("response数据>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>={}",object.toString());
        }
    }
}
